#!/bin/bash
#
# Start a read-only replica that streams from a master cluster
#
# Usage: ./start-replica.sh <replica_id> <master_address> [secret]
#
# Example:
#   # Start master cluster first (in another terminal) with a cluster secret:
#   MARMOT_CLUSTER_SECRET=my-secret ./examples/start-seed.sh
#
#   # Start replica 1 (must use same secret as master):
#   ./start-replica.sh 1 localhost:8081 my-secret
#
#   # Or set via environment:
#   MARMOT_REPLICA_SECRET=my-secret ./start-replica.sh 1 localhost:8081

set -e

REPLICA_ID=${1:-1}
MASTER_ADDR=${2:-"localhost:8081"}
REPLICA_SECRET=${3:-${MARMOT_REPLICA_SECRET:-""}}

# Calculate ports based on replica ID
# Replica 1: mysql=3317, grpc=8091
# Replica 2: mysql=3318, grpc=8092
# etc.
MYSQL_PORT=$((3316 + REPLICA_ID))
GRPC_PORT=$((8090 + REPLICA_ID))

# Directories
DATA_DIR="/tmp/marmot-replica-${REPLICA_ID}"
CONFIG_FILE="/tmp/marmot-replica-${REPLICA_ID}.toml"

if [ -z "${REPLICA_SECRET}" ]; then
    echo "ERROR: Replica secret is required for PSK authentication"
    echo "Usage: ./start-replica.sh <replica_id> <master_address> <secret>"
    echo "   or: MARMOT_REPLICA_SECRET=<secret> ./start-replica.sh <replica_id> <master_address>"
    exit 1
fi

echo "=== Marmot Read-Only Replica ==="
echo "Replica ID:    ${REPLICA_ID}"
echo "Master:        ${MASTER_ADDR}"
echo "MySQL Port:    ${MYSQL_PORT}"
echo "gRPC Port:     ${GRPC_PORT}"
echo "Data Dir:      ${DATA_DIR}"
echo "Config:        ${CONFIG_FILE}"
echo "Auth:          PSK enabled"
echo ""

# Kill any existing processes on our ports
echo "Stopping any existing processes on ports ${MYSQL_PORT}, ${GRPC_PORT}..."
lsof -ti:${MYSQL_PORT} -ti:${GRPC_PORT} 2>/dev/null | xargs kill 2>/dev/null || true
sleep 1

# Clean up previous data
echo "Cleaning up previous data directory..."
rm -rf "${DATA_DIR}"

mkdir -p "${DATA_DIR}"

# Generate config file
cat > "${CONFIG_FILE}" << EOF
# Marmot Read-Only Replica ${REPLICA_ID} Configuration
# Auto-generated by start-replica.sh

node_id = ${REPLICA_ID}
data_dir = "${DATA_DIR}"

[cluster]
grpc_bind_address = "0.0.0.0"
grpc_port = ${GRPC_PORT}
grpc_advertise_address = "localhost:${GRPC_PORT}"
# No seed_nodes - replicas don't participate in cluster gossip

[mysql]
enabled = true
bind_address = "0.0.0.0"
port = ${MYSQL_PORT}

[replica]
enabled = true
master_address = "${MASTER_ADDR}"
secret = "${REPLICA_SECRET}"
reconnect_interval_seconds = 5
reconnect_max_backoff_seconds = 30
initial_sync_timeout_minutes = 30

[replication]
default_write_consistency = "QUORUM"
default_read_consistency = "LOCAL_ONE"

[mvcc]
gc_interval_seconds = 30
gc_retention_hours = 1
heartbeat_timeout_seconds = 10
version_retention_count = 10
conflict_window_seconds = 10

[logging]
verbose = true
format = "console"
EOF

echo "Generated config:"
echo "---"
cat "${CONFIG_FILE}"
echo "---"
echo ""

# Find or build marmot-v2 binary
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

if [ -f "$REPO_ROOT/marmot-v2" ]; then
    MARMOT_BIN="$REPO_ROOT/marmot-v2"
else
    echo "Building marmot-v2..."
    cd "$REPO_ROOT"
    go build -tags sqlite_preupdate_hook -o marmot-v2 .
    MARMOT_BIN="$REPO_ROOT/marmot-v2"
    echo "✓ Build complete"
fi

echo "Starting Marmot replica ${REPLICA_ID}..."
echo "Connect with: mysql -h localhost -P ${MYSQL_PORT} -u root"
echo ""
echo "NOTE: This is a READ-ONLY replica. Writes will be rejected."
echo ""

exec ${MARMOT_BIN} --config "${CONFIG_FILE}"
